﻿using System.Linq;
using System.Data;
using SoccerScore.Compact.Linq;
using System;

namespace Soccer_Score_Forecast
{
    public class MacauslotToSql : ElementParserFunction,IDisposable
    {
        #region Implementing IDisposable and the Dispose Pattern Properly
        private bool disposed = false; // to detect redundant calls
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        ~MacauslotToSql()
        {
            Dispose(false);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    // Free other state (managed objects).
                }
                // Free your own state (unmanaged objects).
                // Set large fields to null.
                disposed = true;
            }
        }
        #endregion
        private HtmlAgilityPackGeneric MacauslotHtml;
        public MacauslotToSql(string _html)
        {
            SqlAgilityPackTableXpath tbTag = new SqlAgilityPackTableXpath("web.macauslot.com");
            MacauslotHtml = new HtmlAgilityPackGeneric(_html, tbTag.macauTag, 0);
        }

        public decimal updateMacauslot()
        {
            DataTable dt = MacauslotHtml.GetTableInnerText_macau();
            DateTime dtt = DateTime.Now.Date;
            using (DataClassesMatchDataContext match = new DataClassesMatchDataContext(Conn.conn))
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow aa = dt.Rows[i];
                    if (aa[3].ToString() != null)
                        if (aa[3].ToString().IndexOf("★") != -1)
                        {
                            MacauPredication mp = new MacauPredication();
                            mp.Record_datetime = dtt;
                            mp.Home_team = extract(aa[0].ToString());//在第1行
                            mp.Away_team = extract(dt.Rows[i + 1][0].ToString());//在第2行
                            mp.Macauslot = dt.Rows[i + 2][1].ToString().Trim();//在第3行
                            mp.Predication = aa[3].ToString(); //在第1行
                            match.MacauPredication.InsertOnSubmit(mp);
                        }
                }
                match.SubmitChanges();
                return match.MacauPredication.Max(e => e.MacauPredication_id);
            }
        }

        private string extract( string team)
        {
            string extractstr = team;
            extractstr = extractstr.Replace("(主)", "").Replace("(中)", "").Trim();
            extractstr = extractstr.Replace("(", "").Replace(")", "").Trim();
            return extractstr;
        }
    }
}
